package com.yksj.healthtalk.ui.server;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.universalimageloader.core.DisplayImageOptions;
import org.universalimageloader.core.ImageLoader;
import org.universalimageloader.core.display.RoundedBitmapDisplayer;
import org.universalimageloader.utils.StorageUtils;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.entity.ShopEntityClassify;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.http.JsonHttpResponseHandler;
import com.yksj.healthtalk.net.http.JsonsfHttpResponseHandler;
import com.yksj.healthtalk.net.http.ObjectHttpResponseHandler;
import com.yksj.healthtalk.net.http.RequestParams;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.utils.HStringUtil;
import com.yksj.healthtalk.utils.ToastUtil;
/**
 * 自选商品  商品浏览主页
 * @author Administrator
 *
 */
public class ServerCenterFreeShopReadActivity extends BaseFragmentActivity implements OnClickListener, OnItemClickListener {

	private ListView mListView;
	private List<ShopEntityClassify> shopEntitys;
	private Myadapter adapter;
	private String MERCHANT_ID;//商户id
	private EditText seach_text;
	private Button seach_onclick;
	private int picid;

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.server_center_freeshop_read_layout);
		initTitle();
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN|WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
		initView();
		MERCHANT_ID=getIntent().getStringExtra("id");
		initData();
	}

	  private void initData() {
	    	HttpRestClient.doHttpGetFreeShopData(MERCHANT_ID,new ObjectHttpResponseHandler() {
				@Override
				public Object onParseResponse(String cotent) {
					return ShopEntityClassify.parseJsonToInfoRead(cotent);
				}
				public void onSuccess(int statusCode, Object response) {
					super.onSuccess(statusCode, response);
					if(response == null)return;
					shopEntitys = (List)response;
					adapter = new Myadapter(ServerCenterFreeShopReadActivity.this,shopEntitys);
					mListView.setAdapter(adapter);
				};
			});
	    }

	private void initView() {
		titleLeftBtn.setOnClickListener(this);
		titleTextV.setText(getIntent().getStringExtra("title"));
		shopEntitys = new ArrayList<ShopEntityClassify>();
		mListView = (ListView)findViewById(R.id.listview);
		mListView.setOnItemClickListener(this);
		seach_onclick = (Button)findViewById(R.id.seach_onclick);
		seach_onclick.setOnClickListener(this);
		seach_text = (EditText) findViewById(R.id.seach_text);
		seach_text.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				if(s.length()>0){
					seach_onclick.setVisibility(View.VISIBLE);
				}else{
					seach_onclick.setVisibility(View.GONE);
				}
			}
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}
			@Override
			public void afterTextChanged(Editable s) {
				
			}
		});
		findViewById(R.id.deleteText).setOnClickListener(this);
		titleRightBtn2.setVisibility(View.VISIBLE);
		titleRightBtn.setVisibility(View.VISIBLE);
		
		titleRightBtn2.setOnClickListener(this);
		titleRightBtn.setOnClickListener(this);
		
		titleRightBtn.setBackgroundResource(R.drawable.shopping_trolley_sel);
		titleRightBtn2.setBackgroundResource(R.drawable.server_order);
	}

	@Override
	protected void onResume() {
		super.onResume();
		initShopCarData();
	}
	
	//请求购物车是否有商品
	private void initShopCarData(){
		RequestParams params=new RequestParams();
		params.put("option", "ISHAVEGOODS");
		params.put("merchantID", MERCHANT_ID);
		params.put("customerID", SmartFoxClient.getLoginUserId());
		HttpRestClient.doHttpShopCarData(params,new JsonsfHttpResponseHandler(this){
			@Override
			public void onSuccess(int statusCode,com.alibaba.fastjson.JSONObject response) {
				super.onSuccess(statusCode, response);
				int count=response.getIntValue("count");
				if(count>0){
					titleRightBtn.setBackgroundResource(R.drawable.shopping_trolley_sel);
				}else{
					titleRightBtn.setBackgroundResource(R.drawable.shopping_trolley);
				}
			}
		});
		
	}
	
	@Override
	public void onClick(View v) {
		Intent intent;
		switch (v.getId()) {
		case R.id.title_back:
//			onBackPressed();
			finish();
			break;
		case R.id.deleteText:
			seach_text.setText("");
			break;
		case R.id.seach_onclick:
			if(!HStringUtil.isEmpty(seach_text.getText().toString())){
				intent = new Intent(this,ServerShopSeachActivity.class);
				intent.putExtra("main", seach_text.getText().toString().trim());
				intent.putExtra("type", -3);
				intent.putExtra("MERCHANT_ID", MERCHANT_ID);
				startActivity(intent);
			}
			break;
		case R.id.title_right:
			HttpRestClient.doHttpCartList(MERCHANT_ID,new TtrolleyHandler(2));
		break;
		case R.id.title_right2:
			intent = new Intent(getApplicationContext(),ServerCenterOrderListActivity.class);
			intent.putExtra("merchant_id", MERCHANT_ID);
			startActivity(intent);
		break;
		}
	}

	class TtrolleyHandler extends JsonHttpResponseHandler {
		int type; // 1加入购物车 2查询购物车列表
		private ImageView buyImg;
		public TtrolleyHandler(int type) {
			super(ServerCenterFreeShopReadActivity.this);
			this.type = type;
		}
		@Override
		public void onSuccess(int statusCode, JSONObject response) {
			try {
				if (response.has("info")) { 
					ToastUtil.showToastPanl(response.getString("info"));
				} else if (response.has("money")) {
					Intent intent = new Intent(getApplicationContext(),ServerCenterTrolleyActivity.class);
					intent.putExtra("MERCHANT_ID", MERCHANT_ID);
					intent.putExtra("response", response.toString());
					startActivityForResult(intent, 1);
//					{}
				}else {
					Intent intent = new Intent(getApplicationContext(),ServerCenterTrolleyActivity.class);
					intent.putExtra("MERCHANT_ID", MERCHANT_ID);
					startActivity(intent);
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
			super.onSuccess(statusCode, response);
		}
		@Override
		public void onSuccess(int statusCode, JSONArray response) {
			Intent intent = new Intent(getApplicationContext(),ServerCenterTrolleyActivity.class);
			startActivity(intent);
			super.onSuccess(statusCode, response);
		}
	}
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		Intent intent=new Intent(this,ServerCenterShopList.class);
		intent.putExtra("entity", shopEntitys.get(position));
		intent.putExtra("MERCHANT_ID", MERCHANT_ID);
		intent.putExtra("PICID", picid);
		startActivity(intent);
	}
	
	class Myadapter extends BaseAdapter{

		private final List<ShopEntityClassify> shopEntitys;
		private final Context mcontext;
		private final LayoutInflater layoutInflater;
		private ImageLoader imageLoader;
		private final DisplayImageOptions options;
		public Myadapter(Context context,List<ShopEntityClassify> shopEntitys) {
			this.mcontext=context;
			this.shopEntitys=shopEntitys;
			this.layoutInflater = LayoutInflater.from(mcontext);
			imageLoader=imageLoader.getInstance();
			
			options = new DisplayImageOptions.Builder(context)
			.showStubImage(R.drawable.icon_default_shop)
			.bitmapConfig(Bitmap.Config.RGB_565)
			.cacheOnDisc(new File(StorageUtils.getHeadersPath()))
			.cacheInMemory()
			.displayer(new RoundedBitmapDisplayer(5))
			.build();
		}
		
		@Override
		public int getCount() {
			return shopEntitys.size();
		}

		@Override
		public Object getItem(int position) {
			return shopEntitys.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if(convertView==null){
				convertView=layoutInflater.inflate(R.layout.freeshop_read_adapter_layout, null);	
			}
			ShopEntityClassify entityClassify = shopEntitys.get(position);
			TextView view=(TextView) convertView.findViewById(R.id.text);
			ImageView imageView =(ImageView)convertView.findViewById(R.id.image_icon);
			view.setText(entityClassify.getCLASS_NAME());
			imageLoader.displayImage(entityClassify.getADDRESS_ICON(), imageView,options);
			if(position==shopEntitys.size()-1){
				convertView.setBackgroundResource(R.drawable.textview_background_down);
			}else if(position==0){
				convertView.setBackgroundResource(R.drawable.textview_background_up);
			}else{
				convertView.setBackgroundResource(R.drawable.textview_background_middle);
			}
			return convertView;
		}
		
	}
}
